package cn.tk.dbtest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBTest {
	static Connection conn=null;
	static Statement stmt=null;
	public DBTest() {
		try{
		Class.forName("com.mysql.jdbc.Driver");
		}catch( Exception e){
			e.printStackTrace();
			System.out.println(e.toString()+"----"+e.getMessage());
		}
	}
	
	public Connection connect(String host,String port,String dbname,String user,String passwd){

		if(("").equals(host) || host==null){
			host="localhost";
		}
		if(("").equals(port)||port==null){
			port="3306";
		}
		if(("").equals(user)||user==null){
			user="root";
		}
		if(("").equals(passwd)||passwd==null){
			passwd="";
		}
		try{
			conn=  DriverManager.getConnection("jdbc:mysql://"+host+":"+port+"/"+dbname,user ,passwd );
		}catch(Exception e){
			e.printStackTrace();
			System.out.println(e.toString()+"----"+e.getMessage());
		}
		return conn;
	}

	public ResultSet query(String sql){
		ResultSet rs=null;

		try {
			stmt=conn.createStatement();
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {

			e.printStackTrace();
			System.out.println(e.toString()+"----"+e.getMessage());
		}
		return rs;
	}
	
	public int update(String sql){
		int count=0;
		try {
			stmt=conn.createStatement();
			count = stmt.executeUpdate(sql);
		} catch (SQLException e) {

			e.printStackTrace();
			System.out.println(e.toString()+"----"+e.getMessage());
		}
		return count;
	}

	public void close(){
		try {
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println(e.toString()+"----"+e.getMessage());
		}
		stmt=null;
		conn=null;
	}

	public static Connection getConnection() {
		return conn;
	}

	public static Statement getStatement() {
		return stmt;
	}
	
	
	
}
